package server;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

import sheduler.EmailTask;
import smtp.SmtpSender;

public class StatusServlet implements Servable {
	private Server server;
	
	public StatusServlet(Server s) {
		this.server = s;
	}
	
	private String toDate(long date) {
		return new Date(date).toString();
	}

	@Override
	public void serve(Request request, Response response) {
		OutputStream output = response.getBodyStream();
		try {		
			
			
			Calendar cal = Calendar.getInstance();
			long curtime = cal.getTimeInMillis();		
			
			output.write("<h1>Pending emails</h1>".getBytes());
			output.write("<table border=1><tr><td><b>Submission</b></td><td><b>Sending</b></td><td><b>Sender</b></td><td><b>Receiver</b></td><td><b>Subject</b></td><td><b>Remaining time</b></td><td><b>Status</b></td></tr>".getBytes());
			
			
			// Iterate through all tasks
			List<EmailTask> tasks = this.server.getManager().getTasks();
			for (EmailTask task : tasks) {
				output.write(("<tr>").getBytes());
				output.write(("<td>" + toDate(task.getSubmissionTime()) + "</td>").getBytes());
				output.write(("<td>" + toDate(task.getSendingTime()) + "</td>").getBytes());
				output.write(("<td>" + task.getSender() + "</td>").getBytes());
				output.write(("<td>" + task.getReceiver() + "</td>").getBytes());
				output.write(("<td>" + task.getSubject() + "</td>").getBytes());
				output.write(("<td>" + task.getRemainingTime(curtime) + "</td>").getBytes());
				output.write(("<td>" + task.getStatus() + "</td>").getBytes());
				output.write(("</tr>").getBytes());
			}
			output.write("</table>".getBytes());
			
			output.write("<p><a href=\"/\">Back</a></p>".getBytes());
		} catch (IOException e) {
			Logger.getLogger(Server.LOG).severe("Cannot serve StatusServlet");			
		}		
	}

	@Override
	public String getContentType() {
		return "text/html";
	}

}
